package org.Lin.controller;

import org.Lin.model.User;
import org.Lin.service.UserService;
import org.json.JSONObject;

import java.io.*;
import java.net.Socket;

public class LoginController extends BaseController {

    private final UserService userService = new UserService();

    public void handleLogin(JSONObject request, Socket socket) throws IOException {
        int userID = request.getInt("userID");
        String password = request.getString("password");

        User user = userService.loginUser(userID, password);
        if (user != null) {
            userService.updateLastLogin(userID);

            JSONObject response = new JSONObject();
            response.put("type", "login_success");
            response.put("userID", user.getUserID());
            response.put("name", user.getName());
            response.put("email", user.getEmail());
            sendResponse(socket, response);
        } else {
            JSONObject response = createErrorResponse("登录失败：用户ID或密码错误");
            sendResponse(socket, response);
        }
    }

    private void sendResponse(Socket socket, JSONObject response) throws IOException {
        PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
        out.println(response.toString());
    }
}
